<!--
/**
 *
 图片（image）: 10M，支持PNG\JPEG\JPG\GIF格式
 语音（voice）：2M，播放长度不超过60s，支持AMR\MP3格式
 视频（video）：10MB，支持MP4格式
 缩略图（thumb）：64KB，支持JPG格式
 */
 -->

<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="消息标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入消息标题" clearable @keyup.enter.native="title" />
      </el-form-item>

      <el-form-item label="消息类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="消息类型" clearable>
          <el-option v-for="dict in sys_new_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:post:remove']">删除</el-button>
      </el-col>

      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="55" align="center" />

      <el-table-column label="消息标题" align="center" prop="title" />
      <el-table-column label="消息类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="sys_new_type" :value="scope.row.type" />
        </template>
      </el-table-column>

      <el-table-column label="消息内容" prop="context" width="120" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.type === 'text'">{{
            scope.row.description
          }}</span>

          <span v-if="scope.row.type === 'image'">
            <el-image v-if="scope.row.context !== '' && scope.row.context != null" style="width: 50px; height: 50px"
              :src="scope.row.context" :preview-src-list="imgUrlList" />
          </span>
        </template>
      </el-table-column>

      <el-table-column label="发布数量" align="center" prop="sendSize" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.sendSize || 0 }}个</span>
        </template>
      </el-table-column>
      <el-table-column label="发布人" align="center" width="180">
        <template slot-scope="scope"> 系统管理员 </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleNews(scope.row)">消息预览</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      :page-sizes="[10]" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="消息标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入消息标题" :disabled="businessType === 'view'" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="消息类型" prop="type">
              <el-radio-group v-model="form.type" @change="handleType">
                <el-radio v-for="dict in sys_new_type" :key="dict.value" :label="dict.value"
                  :disabled="businessType === 'view'">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!-- 文本消息 -->
            <el-form-item v-if="form.type === 'text'" label="消息内容" prop="context">
              <el-input v-model="form.context" type="textarea" :autosize="{ minRows: 10, maxRows: 15 }"
                placeholder="请输入消息内容" maxlength="1000" show-word-limit :disabled="businessType === 'view'" />
            </el-form-item>

            <!-- 图片消息 -->
            <el-form-item v-if="form.type === 'image'" label="图片消息" prop="context">
              <div class="file-upload">
                <el-upload ref="fileUpload0" :action="action" :headers="headers" name="file" :data="{ type: 'image' }"
                  :before-upload="beforeAvatarUploadImage" :limit="1" :on-error="handleUploadError"
                  :on-exceed="exceedHandler" :on-success="
                    (res) => {
                      handleUploadSuccess(res, 'image')
                    }
                  " :on-remove="
                    (file) => {
                      handleRemove(file, 'image')
                    }
                  " :file-list="fileListImage" class="upload-file-uploader" list-type="picture-card" :on-preview="
                    (file) => {
                      handlePreview(file, 'image')
                    }
                  " :disabled="businessType === 'view'">
                  <!--  :file-list="fileListImage" -->
                  <!-- 上传按钮 -->
                  <!-- <el-button
                    type="primary"
                    icon="el-icon-upload"
                    plain
                    >图片上传</el-button
                  > -->
                  <i class="el-icon-plus" />
                  <!-- 上传提示 -->
                  <div class="el-upload__tip" slot="tip">
                    请上传
                    <template>
                      格式为<b style="color: #f56c6c">{{
                        imageTypeList.join('/')
                      }}</b>的 大小不超过
                      <b style="color: #f56c6c">{{ fileSizeImage }}MB</b>的<b style="color: #f56c6c">1</b>个文件
                    </template>
                  </div>
                </el-upload>
              </div>
            </el-form-item>

            <!-- 视频消息 -->
            <el-form-item label="视频消息" prop="context" v-if="form.type === 'video'">
              <div class="file-upload">
                <el-upload ref="fileUpload1" :action="action" :headers="headers" name="file" :data="{ type: 'video' }"
                  :before-upload="beforeAvatarUploadVideo" :limit="1" :on-error="handleUploadError"
                  :on-exceed="exceedHandler" :on-success="
                    (file) => {
                      handleUploadSuccess(file, 'video')
                    }
                  " :on-remove="
                    (file) => {
                      handleRemove(file, 'video')
                    }
                  " :file-list="fileListVideo" class="upload-file-uploader" :on-preview="
                    (file) => {
                      handlePreview(file, 'video')
                    }
                  " :disabled="businessType === 'view'">
                  <!-- 上传按钮 -->
                  <el-button type="primary" icon="el-icon-upload" plain size="mini">视频上传</el-button>
                  <!-- 上传提示 -->
                  <div class="el-upload__tip" slot="tip">
                    请上传
                    <template>
                      格式为<b style="color: #f56c6c">{{
                        videoTypeList.toString()
                      }}</b>的 大小不超过
                      <b style="color: #f56c6c">{{ fileSizeVideo }}MB</b>的<b style="color: #f56c6c">1</b>个文件
                    </template>
                  </div>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="businessType !== 'view'" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog :title="title" :visible.sync="openView" width="60%" append-to-body>
      <el-descriptions class="margin-top" title="" :column="1" border>
        <el-descriptions-item label-class-name="my-label" content-class-name="my-content">
          <template slot="label"> 消息标题 </template>
          {{ form.title }}
        </el-descriptions-item>

        <el-descriptions-item label-class-name="my-label" content-class-name="my-content">
          <template slot="label"> 消息类型 </template>
          <dict-tag :options="sys_new_type" :value="form.type" />
        </el-descriptions-item>

        <el-descriptions-item label-class-name="my-label" content-class-name="my-content">
          <template slot="label"> 消息内容 </template>
          <div v-if="form.type === 'text'">{{ form.context }}</div>
          <div v-if="form.type === 'image'">
            <el-image v-if="form.context !== '' && form.context != null" style="width: 50px; height: 50px"
              :src="form.context" :preview-src-list="[form.context]" />
          </div>
          <div v-if="form.type === 'video'">
            <el-button type="success" icon="el-icon-view" plain
              @click.stop="handlePreview({ url: form.context }, 'video')">视频预览</el-button>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
  import {
    getNewsList,
    addNews,
    getByMaterialId,
    deleteNews
  } from '@/api/newManage.js'
  import {
    getToken
  } from '@/utils/auth'
  export default {
    name: 'news',

    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        businessType: 'add',
        // 表格数据
        list: [],
        sys_new_type: [{
            label: '文本消息',
            value: 'text',
            raw: {
              listClass: 'primary'
            }
          },
          {
            label: '图片消息',
            value: 'image',
            raw: {
              listClass: 'success'
            }
          },
          {
            label: '视频消息',
            value: 'video',
            raw: {
              listClass: 'warning'
            }
          }
        ],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        openView: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: undefined,
          type: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          title: [{
            required: true,
            message: '消息标题不能为空',
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: '请选择消息类型',
            trigger: 'change'
          }],
          context: [{
            required: true,
            message: '消息名称不能为空',
            trigger: 'blur'
          }]
        },

        // headers
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        // 上传地址
        // action: process.env.VUE_APP_BASE_API + '/common/upload',
        action: process.env.VUE_APP_BASE_API + '/wechat/materialLib/upload',
        backUrl: 'http://wxai.cmqps.xyz:8090',

        imgUrlList: [],

        // PNG\JPEG\JPG\GIF
        imageTypeList: ['png', 'jpeg', 'jpg', 'gif'],
        fileSizeImage: '10',
        fileListImage: [],
        videoTypeList: ['mp4'],
        fileSizeVideo: '10',
        fileListVideo: [],
        dialogImageUrl: '',
        dialogVisible: false
      }
    },
    created() {
      this.getList()
    },
    methods: {
      /** 查询列表 */

      async getList() {
        this.loading = true
        this.imgUrlList = []

        try {
          const res = await getNewsList(this.queryParams)
          const list = res.data.records || []
          this.total = res.data.total

          // 使用 Promise.all 处理异步操作
          this.list = await Promise.all(
            list.map(async (item) => ({
              ...item,
              description: this.handleDescription(item),
              context: await this.handleContext(item)
            }))
          )
        } catch (error) {
          console.error('获取列表失败:', error)
        } finally {
          this.loading = false
        }
      },

      handleDescription(row) {
        if (row.type === 'text') {
          const str = row.context || ''
          if (str && str.length > 50) {
            // 从头向后截取 50 个字符
            return str.substring(0, 50) + '...'
          } else {
            // 直接返回原字符串
            return str
          }
        }
      },

      async handleContext(row) {
        if (row.type === 'image' || row.type === 'video') {
          // 图片预览 列表
          const context = row.context || ''
          if (context === '') return context
          const url = await this.getMaterial(row.context)
          if (row.type === 'image' && url !== '') {
            this.imgUrlList.push(url)
          }
          return url
        } else {
          return row.context
        }
      },

      async getMaterial(id) {
        this.loading = true
        const res = await getByMaterialId(id)
        if (res.code !== 200) {
          return ''
        } else {
          const profile = res.data.profile || ''
          if (profile !== '') {
            return this.backUrl + res.data.profile
          } else {
            return ''
          }
        }
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.openView = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          title: undefined,
          type: 'text',
          description: undefined,
          context: undefined
        }

        this.fileListImage = []
        this.fileListVideo = []
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.businessType = 'add'
        this.reset()
        this.open = true
        this.title = '添加消息'
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /* 详情按钮操作 */
      handleNews(row) {
        this.businessType = 'view'
        this.reset()
        this.form = Object.assign({}, row)

        const fileUrl = row.context || ''
        const fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1)
        if (row.type === 'image') {
          this.fileListImage = [{
            name: fileName,
            url: fileUrl
          }]
          this.fileListVideo = []
        } else if (row.type === 'video') {
          this.fileListVideo = [{
            name: fileName,
            url: fileUrl
          }]
          this.fileListImage = []
        }
        this.openView = true
        this.title = '消息预览'
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const params = Object.assign({}, this.form)

            if (params.type === 'text') {
              const str = params.context || ''
              if (str && str.length > 50) {
                // 从头向后截取 50 个字符
                params.description = str.substring(0, 50) + '...'
              } else {
                // 直接返回原字符串
                params.description = str
              }
            } else {
              params.context = params.mediaId
            }
            addNews(params).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
          return deleteNews(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 消息类型选择操作 */
      handleType(e) {
        console.log('消息类型选择操作', e)
      },

      // 文件上传前操作
      beforeAvatarUploadImage(file) {
        console.log('file', file)

        // return new Promise((resolve, reject) => {
        // 判断上传格式*****************
        let fileName = file.name
        fileName = fileName.substring(fileName.lastIndexOf('.') + 1)
        const fileTypeList = this.imageTypeList
        const isTypeOk = fileTypeList.indexOf(fileName) >= 0

        const fileSize = this.fileSizeImage
        const isLt100M = file.size / 1024 / 1024 < fileSize

        if (!isTypeOk) {
          this.$modal.msgError(
            `文件格式不正确, 请上传${fileTypeList.join('/')}格式文件!`
          )
          return false
        } else if (!isLt100M) {
          this.$message.error('上传文件大小不能超过' + fileSize + 'MB!')
          return false
        } else {
          this.$modal.loading('正在上传文件，请稍候...')
          return isTypeOk && isLt100M
        }
      },
      beforeAvatarUploadVideo(file) {
        console.log('file', file)

        // return new Promise((resolve, reject) => {
        // 判断上传格式*****************
        let fileName = file.name
        fileName = fileName.substring(fileName.lastIndexOf('.') + 1)
        const fileTypeList = this.videoTypeList
        const isTypeOk = fileTypeList.indexOf(fileName) >= 0

        const fileSize = this.fileSizeVideo
        const isLt100M = file.size / 1024 / 1024 < fileSize

        if (!isTypeOk) {
          this.$modal.msgError(
            `文件格式不正确, 请上传${fileTypeList.join('/')}格式文件!`
          )
          return false
        } else if (!isLt100M) {
          this.$message.error('上传文件大小不能超过' + fileSize + 'MB!')
          return false
        } else {
          this.$modal.loading('正在上传文件，请稍候...')
          return isTypeOk && isLt100M
        }
      },

      // 上传失败
      handleUploadError(err) {
        this.$modal.msgError('上传失败，请重试')
        this.$modal.closeLoading()
      },

      // 文件超出个数限制
      exceedHandler(files) {
        this.$message.error('只能上传1个文件')
      },
      // 上传成功之后的操作
      handleUploadSuccess(res, type) {
        /**
         *
         *
         * {"msg":"操作成功",
         * "fileName":"/profile/upload/2025/04/20/0bc3cyacuaaaueabecgzajtvafwdfilaakqa.f10004_20250420200055A001.mp4",
         * "code":200,
         * "newFileName":"0bc3cyacuaaaueabecgzajtvafwdfilaakqa.f10004_20250420200055A001.mp4",
         * "url":"http://localhost:8088/profile/upload/2025/04/20/0bc3cyacuaaaueabecgzajtvafwdfilaakqa.f10004_20250420200055A001.mp4",
         * "originalFilename":"0bc3cyacuaaaueabecgzajtvafwdfilaakqa.f10004.mp4"}
         *
         *
         */
        console.log('res', res)
        this.$modal.closeLoading()
        if (res.code !== 200) {
          this.$modal.msgError(res.msg)
          return
        }

        // const fileUrl = res.url
        // const fileName = res.newFileName

        const fileUrl = this.backUrl + res.data.profile
        const fileName = res.data.fileName
        const mediaId = res.data.mediaId || ''
        this.form.context = fileUrl
        this.form.mediaId = mediaId
        if (type === 'image') {
          this.fileListImage = [{
            name: fileName,
            url: fileUrl
          }]
          this.fileListVideo = []
        } else {
          this.fileListVideo = [{
            name: fileName,
            url: fileUrl
          }]
          this.fileListImage = []
        }
      },
      //    删除文件
      handleRemove(e, type) {
        if (type === 'image') {
          this.form.context = ''
          this.fileListImage = []
        } else {
          this.form.context = ''
          this.fileListVideo = []
        }
      },
      // 图片预览
      handlePreview(file, type) {
        if (type === 'image') {
          this.dialogImageUrl = file.url
          this.dialogVisible = true
        } else {
          window.open(file.url)
        }
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  .my-label {
    width: 100px;
  }
</style>
